<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use app\admin\model\goods\Goods as GoodsModel;
use app\admin\model\hospital\Hospital as HospitalModel;
use app\admin\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 项目订单主单
 *
 * @icon fa fa-circle-o
 */
class OrderMaster extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\order\Order
     */
    protected $model = null;
    protected $noNeedRight = ['getGoodsInfo','refund'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\OrderMaster();
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("reportStatusList", $this->model->getReportStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $user = $this->auth->getUserInfo();
        $groupIds = [];
        foreach ($this->auth->getGroupIds() as $key => $value) {
            $groupIds[] = $value;
        }
        $whereCustom = [];
        if (in_array(3, $groupIds, true) && count($groupIds) == 1) {
            // 医院账号
            $hospital = \app\admin\model\hospital\Hospital::where('admin_id', $user['id'])->find();
            if ($hospital) {
                $whereCustom = [
                    'order.hospital_id' => $hospital['id'],
                ];
            } else {
                $whereCustom = [
                    'order.hospital_id' => -1,
                ];
            }
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->alias('order')
            ->field('order.*')
            ->where($where)
            ->where($whereCustom)
            ->where('pay_status', 1)
            ->join('user', 'order.user_id=user.id')
            ->with(['ordergoods', 'hospital', 'user', 'sale', 'orderTube'])
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function getGoodsInfo()
    {
        $ids = $this->request->post('ids', '');
        $doctor_id = $this->request->post('doctor_id', '');

        $goodsList = GoodsModel::where('id', 'in', $ids)->select();
        $user = \app\admin\model\User::get($doctor_id);
        if (empty($user->hospital_id)) {
            $this->error('请先绑定医院');
        }
        $hospital = HospitalModel::get($user->hospital_id);
        $hospitalDiscount = \app\api\model\hospital\HospitalDiscount::where('hospital_id', $user->hospital_id)->where('goods_id', 'in', $ids)->select();
        $goodsDiscount = [];
        foreach ($hospitalDiscount as $item) {
            $goodsDiscount[$item->goods_id] = $item;
        }
        $totalPrice = 0;
        $price = 0;
        $model = new \app\api\model\order\Order();
        $rongqiList = [];
        $rongqiIds = [];
        foreach ($goodsList as &$goods) {
            $rongqi = $model->getRongqiList($goods);
            foreach ($rongqi as $rongqi_item) {
                $item = $rongqi_item->toArray();
                if ($index = array_search($rongqi_item->id, $rongqiIds) === false) {
                    $rongqiList[] = $item;
                    $rongqiIds[] = $rongqi_item->id;
                }
            }

            $discountPrice = ($goods->price * $hospital->discount / 100);
            if (isset($goodsDiscount[$goods->id])) {
                $discountPrice = $goodsDiscount[$goods->id]['type'] == 10 ? $goods->price * $goodsDiscount[$goods->id]['discount'] / 100  : $goodsDiscount[$goods->id]['money'];
            }
            $price +=  $discountPrice > 0 ? $discountPrice : 0.01;
            $totalPrice += $goods->price;
        }

        return json(['rongqiList' => $rongqiList, 'total' => $price]);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;

        $tubeData = [];
        foreach ($params['rongqi']['id'] as $key => $item) {
            $tubeData[] = [
                'id' => $item,
                'tube_number' => $params['rongqi']['tube_number'][$key],
            ];
        }
        $goods_ids = explode(',', $params['goods_ids']); // 项目id
        $username = $params['username'];
        $userphone = $params['userphone'];
        $age = $params['age'];
        $gender = $params['gender'];
        $doctor_id = $params['user_id'];

        if (empty($username)) {
            $this->error('患者姓名不能为空');
        }
        // if (empty($userphone)) {
        //     $this->error('患者手机号不能为空');
        // }
        if (!empty($userphone) && !preg_match('/^1[3-9]\d{9}$/', $userphone)) {
            $this->error('手机号格式错误');
        }
        if (empty($age)) {
            $this->error('患者年龄不能为空');
        }

        if (empty($tubeData) || count($tubeData) == 0) {
            $this->error('请选择检测项目');
        }
        $tubeList = [];
        $tube_number = [];

        foreach ($tubeData as $tube) {
            if (array_search($tube['tube_number'], $tube_number) !== false) {
                $this->error("试管号‘{$tube['tube_number']}’重复");
            }
            $tube_number[] = $tube['tube_number'];
            $res = \app\api\model\order\OrderTube::where('tube_number', $tube['tube_number'])->find();
            if ($res) {
                $this->error("试管号‘{$tube['tube_number']}’重复使用");
            }
        }

        $goodsList = GoodsModel::where('id', 'in', $goods_ids)->select();
        if (empty($goodsList)) {
            $this->error('检测项目不存在');
        }

        $user = \app\admin\model\User::get($doctor_id);
        if (empty($user->hospital_id)) {
            $this->error('医生未绑定医院');
        }
        $hospital = HospitalModel::get($user->hospital_id);
        $hospitalDiscount = \app\api\model\hospital\HospitalDiscount::where('hospital_id', $user->hospital_id)->where('goods_id', 'in', $goods_ids)->select();
        $goodsDiscount = [];
        foreach ($hospitalDiscount as $item) {
            $goodsDiscount[$item->goods_id] = $item;
        }
        $totalPrice = 0;
        $price = 0;
        $rongqiList = [];
        $rongqiIds = [];
        $orderGoodsList = [];
        $goodsItemList = [];
        $saveOrderGoodsDetails = [];
        $model = new \app\api\model\order\Order();
        foreach ($goodsList as &$goods) {
            if ($goods->type != 10) {
                $temOrderGoodsDetails = \app\api\model\goods\GoodsDetails::field('goods_master_id,goods_id,type')->where('goods_master_id', $goods->id)->select();
                $saveOrderGoodsDetails = array_merge($saveOrderGoodsDetails, Collection($temOrderGoodsDetails)->toArray());
            }

            $rongqi = $model->getRongqiList($goods, $goodsItemList);
            foreach ($rongqi as $rongqi_item) {
                $item = $rongqi_item->toArray();
                if (array_search($rongqi_item->id, $rongqiIds) === false) {
                    $rongqiList[] = $item;
                    $rongqiIds[] = $rongqi_item->id;
                }
            }
            $discountPrice = ($goods->price * $hospital->discount / 100);
            $discount_type = 30;
            $discount = $hospital->discount;
            if (isset($goodsDiscount[$goods->id])) {
                $discount_type = $goodsDiscount[$goods->id]['type'];
                $discount = $goodsDiscount[$goods->id]['discount'];
                $discountPrice = $goodsDiscount[$goods->id]['type'] == 10 ? $goods->price * $goodsDiscount[$goods->id]['discount'] / 100  : $goodsDiscount[$goods->id]['money'];
            }
            $_price = $discountPrice > 0 ? $discountPrice : 0.01;
            $price +=  $_price;
            $totalPrice += $goods->price;

            $orderGoodsList[] = [
                'type' => $goods->type,
                'goods_id' => $goods->id,
                'goods_no' => $goods->goods_no,
                'title' => $goods->title,
                'short_title' => $goods->short_title,
                'pinyin_title' => $goods->pinyin_title,
                'image' => $goods->image,
                'goods_category_id' => $goods->goods_category_id,
                'biaoben_type_id' => $goods->biaoben_type_id,
                'num' => $goods->num,
                'biaoben_rongqi_id' => $goods->biaoben_rongqi_id,
                'keshi' => $goods->keshi,
                'fangfa' => $goods->fangfa,
                'waijian_tags' => $goods->waijian_tags,
                'hospital' => $goods->hospital,
                'time' => $goods->time,
                'real_price' => $_price,
                'price' => $goods->price,
                'original_price' => $goods->original_price,
                'discount_type' => $discount_type,
                'discount' => $discount,
            ];
        }

        $saveGoodsItemList = [];
        foreach ($goodsItemList as $goods) {
            $saveGoodsItemList[] = [
                'type' => $goods->type,
                'goods_id' => $goods->id,
                'goods_no' => $goods->goods_no,
                'title' => $goods->title,
                'short_title' => $goods->short_title,
                'pinyin_title' => $goods->pinyin_title,
                'image' => $goods->image,
                'goods_category_id' => $goods->goods_category_id,
                'biaoben_type_id' => $goods->biaoben_type_id,
                'num' => $goods->num,
                'biaoben_rongqi_id' => $goods->biaoben_rongqi_id,
                'keshi' => $goods->keshi,
                'fangfa' => $goods->fangfa,
                'waijian_tags' => $goods->waijian_tags,
                'hospital' => $goods->hospital,
                'time' => $goods->time,
                'price' => $goods->price,
                'original_price' => $goods->original_price,
            ];
        }

        if (count($rongqiList) != count($tubeData)) {
            $this->error('试管容器数量有误');
        }

        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $order_sn = createOrdersn($user->id, 'O');
            $params['out_trade_no'] = $order_sn;
            $params['order_sn'] = $order_sn;
            $params['original_price'] = $totalPrice;
            $params['price'] = $price;
            $params['pay_type'] = 30;
            $params['pay_status'] = 1;
            $params['pay_time'] = time();
            $params['status'] = 10;
            $params['sole_id'] = $hospital->user_id;
            $params['hospital_id'] = $hospital->id;

            $result = $this->model->allowField(true)->save($params);
            $modelMaster = $this->model->find($this->model->id);

            $tubeSaveList = [];
            foreach ($tubeData as $tube) {
                $tubeSaveList[] = [
                    'order_master_id' => $this->model->id,
                    'biaoben_rongqi_id' => $tube['id'],
                    'tube_number' => $tube['tube_number']
                ];
            }
            $orderTube = new \app\api\model\order\OrderTube();
            $orderTubeList = $orderTube->saveAll($tubeSaveList);
            if (!$orderTubeList) {
                throw new \Exception('订单创建失败');
            }

            foreach ($orderGoodsList as &$item) {
                $item['order_master_id'] = $this->model->id;
            }

            $orderGOods = new \app\api\model\order\OrderGoods();
            $orderGoodsListModel = $orderGOods->saveAll($orderGoodsList);
            if (!$orderGoodsListModel) {
                throw new \Exception('订单创建失败');
            }

            foreach ($orderGoodsListModel as $orderGoods) {
                $order = new \app\api\model\order\Order();
                $result = $order->save([
                    'order_master_id' => $modelMaster->id,
                    'order_goods_id' => $orderGoods->id,
                    'user_id' => $modelMaster->user_id,
                    'sole_id' => $modelMaster->sole_id,
                    'hospital_id' => $modelMaster->hospital_id,
                    'username' => $modelMaster->username,
                    'userphone' => $modelMaster->userphone,
                    'age' => $modelMaster->age,
                    'gender' => $modelMaster->gender,
                    'out_trade_no' => $modelMaster->out_trade_no,
                    'transaction_id' => $modelMaster->transaction_id,
                    'order_sn' => createOrdersn($modelMaster->user_id, 'S'),
                    'price' => $orderGoods->real_price,
                    'original_price' => $orderGoods->price,
                    'pay_type' => $modelMaster->pay_type,
                    'order_type' => 10,
                    'pay_status' => 1,
                    'pay_time' => time(),
                    'status' => 10,
                ]);

                if (!$result) {
                    \think\Log::record("子订单保存失败：{$order->out_trade_n}-{$orderGoods->id}");
                    throw new \Exception("子订单保存失败：{$order->out_trade_n}-{$orderGoods->id}");
                } else {
                    $orderGoods->order_id = $order->id;
                    $orderGoods->save();
                }
            }

            $saveGoodsItemListIds = [];
            $saveGoodsItemListData = [];
            foreach ($saveGoodsItemList as &$item) {
                $item['order_master_id'] = $this->model->id;
                if (!in_array($item['goods_id'], $saveGoodsItemListIds)) {
                    $saveGoodsItemListIds[] = $item['goods_id'];
                    $saveGoodsItemListData[] = $item;
                }
            }
            $orderGoodsItem = new \app\api\model\order\OrderGoodsItem();
            $orderGoodsItemListModel = $orderGoodsItem->saveAll($saveGoodsItemListData);
            if (!$orderGoodsItemListModel) {
                throw new \Exception('订单创建失败');
            }

            if (count($saveOrderGoodsDetails)) {
                foreach ($saveOrderGoodsDetails as &$item) {
                    $item['order_master_id'] = $this->model->id;
                }
                $orderGoodsDetails = new \app\api\model\order\OrderGoodsDetails();
                $orderGoodsDetailsListModel = $orderGoodsDetails->saveAll($saveOrderGoodsDetails);
                if (!$orderGoodsDetailsListModel) {
                    throw new \Exception('订单创建失败');
                }
            }
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 退款
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function refund($ids = null)
    {
        $order = $this->model->get($ids);
        if (!$order) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $goodslist = \app\api\model\order\OrderGoods::where('order_master_id', $ids)->select();
            $this->view->assign('row', $order);
            $this->view->assign('goodslist', $goodslist);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $id = $ids;
        // $goods_ids = explode(',', $params['goods_ids']);
        $goods_ids = $params['goods_ids'];
        if ($order->status == 0 || $order->status == -10 || $order->status == -20 || ($order->status == 30 && $order->report_status == 30)) {
            $this->error("该状态不可取消订单");
        }

        $goodsList = \app\api\model\order\OrderGoods::where('order_master_id', $id)->where('id', 'in', $goods_ids)->select();
        if (count($goodsList) != count($goods_ids)) {
            $this->error("参数错误");
        }
        $goodsListAll = \app\api\model\order\OrderGoods::where('order_master_id', $id)->select();
        $goodsCount = count($goodsListAll);

        $rongqiIds = [];
        $rongqiIds2 = [];
        $model = new \app\api\model\order\Order();
        foreach ($goodsList as $goods) {
            $rongqi = $model->getRongqiList($goods);
            foreach ($rongqi as $rongqi_item) {
                $item = $rongqi_item->toArray();
                if ($index = array_search($rongqi_item->id, $rongqiIds2) === false) {
                    $rongqiIds2[] = $rongqi_item->id;
                }
            }
        }

        foreach ($goodsListAll as $goods) {
            if (array_search($goods->id, $goods_ids) !== false) {
                continue;
            }
            $rongqi = $model->getRongqiList($goods);
            foreach ($rongqi as $rongqi_item) {
                $item = $rongqi_item->toArray();
                if ($index = array_search($rongqi_item->id, $rongqiIds) === false) {
                    $rongqiIds[] = $rongqi_item->id;
                }
            }
        }

        $rongqiDelete = [];
        foreach ($rongqiIds2 as $rongqi_id) {
            if (array_search($rongqi_id, $rongqiIds) === false) {
                $rongqiDelete[] = $rongqi_id;
            }
        }



        DB::startTrans();
        try {
            if (count($rongqiDelete) > 0) {
                $res = \app\api\model\order\OrderTube::where('biaoben_rongqi_id', 'in', $rongqiDelete)->where('order_master_id', $id)->update(['isdelete' => 20]);
                if (!$res) {
                    throw new \Exception("取消失败1");
                }
            }

            $time = time();
            $price = 0;
            $out_refund_no = createOrdersn($order->user_id, 'R');

            $saveOrder = [];
            $orderIds = [];
            foreach ($goodsList as $goods) {
                $item = [
                    'quxiaotime' => $time,
                    'tuikuantime' => $time,
                    'id' => $goods->order_id
                ];
                if ($order->pay_type == 10) {
                    // 余额支付
                    $item['status'] = -20;
                } else if ($order->pay_type == 20) {
                    // 微信支付
                    $order->out_refund_no = $out_refund_no;
                    $item['status'] = -10;
                } else if ($order->pay_type == 30) {
                    // 线下支付
                    $item['status'] = -20;
                }
                $orderIds[] = $goods->order_id;
                $saveOrder[] = $item;
                $price += $goods->real_price;

                $goods->status = -10;
                $res = $goods->save();
                if (!$res) {
                    throw new \Exception("取消失败2");
                }
            }
            $res = (new \app\api\model\order\Order)->saveAll($saveOrder);

            if (!$res) {
                throw new \Exception("取消失败3");
            }

            $norefundcount = \app\api\model\order\OrderGoods::where('order_master_id', 'in', $id)->where('status', 10)->count();
            if ($goodsCount == count($goodsList) ||  $norefundcount == 0) {
                // 全部取消
                if ($order->pay_type == 10) {
                    // 余额支付
                    $order->status = -20;
                    $order->tuikuantime = $time;
                } else if ($order->pay_type == 20) {
                    // 微信支付
                    $order->out_refund_no = $out_refund_no;
                    $order->status = -10;
                } else if ($order->pay_type == 30) {
                    // 线下支付
                    $order->status = -20;
                    $order->tuikuantime = $time;
                }
                $order->quxiaotime = $time;
                $order->refund_status = 30;
                $order->refund_price = $order->price;
                $result = $order->save();
                $price = $order->price;
                if (!$result) {
                    throw new \Exception("取消失败4");
                }
            } else {
                $order->refund_status = 20;
                $order->refund_price = $order->refund_price + $price;
                $result = $order->save();
                if (!$result) {
                    throw new \Exception("取消失败5");
                }
            }

            if ($order->pay_type == 10) {
                // 余额退款
                $user = \app\api\model\User::find($order->user_id);
                $user->setUpdateMoneyParams([
                    'memo' => "取消订单{$order->out_trade_no}退回余额",
                    'title' => '订单退款',
                    'datatype' => 30
                ]);
                $user->money = $user->money + $price;
                $result = $user->save();
                if (!$result) {
                    throw new \Exception("取消失败6");
                }
            } else if ($order->pay_type == 20) {
                // 微信退款
                $request = request();
                $notifyurl =  $request->root(true) . '/api/notifyx/notifyxOrderRefund/paytype/wechat';
                $params = [
                    'out_trade_no' => $order['out_trade_no'],
                    'out_refund_no' => $out_refund_no,
                    'notify_url' => $notifyurl,
                    'amount' => [
                        'refund' => $price * 100,
                        'total' => $order->price * 100,
                        'currency' => 'CNY',
                    ],
                ];

                $result = \addons\epay\library\Service::submitRefund($params, 'wechat');
                \think\Log::write('退款请求返回：' . json_encode($result));
                // v2 接口
                // if (!($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS')) { 
                //     \think\Log::write('微信退款失败:'.json_encode($result),'error');
                //     throw new \Exception("微信退款失败");
                // }
                if (!isset($result['status'])) {
                    \think\Log::write('微信退款失败:' . json_encode($result), 'error');
                    throw new \Exception("微信退款失败");
                }
                // v3 接口  SUCCESS: 退款成功 PROCESSING: 退款处理中 ABNORMAL: 退款异常 CLOSED: 退款关闭
                if ($result['status'] == 'ABNORMAL' || $result['status'] == 'CLOSED') {
                    \think\Log::write('微信退款失败:' . json_encode($result), 'error');
                    throw new \Exception("微信退款失败");
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            $this->error($e->getMessage());
        }
        $this->success('退款成功');
    }


    public function import(){
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
        $updatecount = 0;
        $skip = 0;
        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $fielddata = [
            '下单用户id'=>'医生',
            '下单人姓名'=>'患者姓名',
            '下单人手机号'=>'患者手机号',
        ];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        $list[] = [
            'COLUMN_NAME' => 'goods_ids',
            'COLUMN_COMMENT' => '检测项目'
        ];
        $list[] = [
            'COLUMN_NAME' => 'rongqi',
            'COLUMN_COMMENT' => '检测容器'
        ];

        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[isset($fielddata[$v['COLUMN_COMMENT']])?$fielddata[$v['COLUMN_COMMENT']] : $v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        $goods_no_list = [];
        Db::startTrans();
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                
                if ($row) {
                    if(!isset($row['user_id']) || empty($row['user_id'])){
                        throw new Exception("医生不能为空,第{$currentRow}行");
                    }
                    if(isset($row['user_id']) && !empty($row['user_id'])){
                        $user = \app\admin\model\User::where('mobile','=',$row['user_id'])->where('role','=','30')->find();
                        if(empty($user)){
                            throw new Exception("医生不存在,第{$currentRow}行");
                        }
                        if(empty($user->hospital_id)){
                            throw new Exception("医生未绑定医院,第{$currentRow}行");
                        }
                        $row['user_id'] = $user->id;
                    }

                    if(!isset($row['goods_ids']) || empty($row['goods_ids'])){
                        throw new Exception("检测项目不能为空,第{$currentRow}行");
                    }
                    $goodsList = GoodsModel::where('goods_no', 'in', $row['goods_ids'])->select();
                    if (empty($goodsList)) {
                        $this->error('检测项目不存在');
                    }
                     $goods_ids = [];
                     foreach ($goodsList as $k => $v) {
                         $goods_ids[] = $v->id;
                     }

                    if(!isset($row['rongqi']) || empty($row['rongqi'])){
                        throw new Exception("检测容器不能为空,第{$currentRow}行");
                    }
                    $rongqi = explode(',',$row['rongqi']);
                    $tubeData = [];
                    foreach($rongqi as $k=>$v){
                        $arr = explode(':',$v);
                        $biaoben_rongqi = \app\admin\model\goods\BiaobenRongqi::where('title','=',$arr[0])->column('id');
                        if(empty($biaoben_rongqi)){
                            throw new Exception("检测容器{$arr[0]}不存在,第{$currentRow}行");
                        }
                        $tubeData[] = [
                            'tube_number'=>$arr[1],
                            'id'=>$biaoben_rongqi[0]
                        ];
                        $res = \app\api\model\order\OrderTube::where('tube_number', $arr[1])->find();
                        if ($res) {
                            $this->error("试管号‘{$arr[1]}’重复使用,第{$currentRow}行");
                        }
                    }
                    
                    $hospital = HospitalModel::get($user->hospital_id);
                    $hospitalDiscount = \app\api\model\hospital\HospitalDiscount::where('hospital_id', $user->hospital_id)->where('goods_id', 'in', $goods_ids)->select();
                    $goodsDiscount = [];
                    foreach ($hospitalDiscount as $item) {
                        $goodsDiscount[$item->goods_id] = $item;
                    }
                    $totalPrice = 0;
                    $price = 0;
                    $rongqiList = [];
                    $rongqiIds = [];
                    $orderGoodsList = [];
                    $goodsItemList = [];
                    $saveOrderGoodsDetails = [];
                    $model = new \app\api\model\order\Order();
                    foreach ($goodsList as &$goods) {
                        if ($goods->type != 10) {
                            $temOrderGoodsDetails = \app\api\model\goods\GoodsDetails::field('goods_master_id,goods_id,type')->where('goods_master_id', $goods->id)->select();
                            $saveOrderGoodsDetails = array_merge($saveOrderGoodsDetails, Collection($temOrderGoodsDetails)->toArray());
                        }

                        $rongqi = $model->getRongqiList($goods, $goodsItemList);
                        foreach ($rongqi as $rongqi_item) {
                            $item = $rongqi_item->toArray();
                            if (array_search($rongqi_item->id, $rongqiIds) === false) {
                                $rongqiList[] = $item;
                                $rongqiIds[] = $rongqi_item->id;
                            }
                        }
                        $discountPrice = ($goods->price * $hospital->discount / 100);
                        $discount_type = 30;
                        $discount = $hospital->discount;
                        if (isset($goodsDiscount[$goods->id])) {
                            $discount_type = $goodsDiscount[$goods->id]['type'];
                            $discount = $goodsDiscount[$goods->id]['discount'];
                            $discountPrice = $goodsDiscount[$goods->id]['type'] == 10 ? $goods->price * $goodsDiscount[$goods->id]['discount'] / 100  : $goodsDiscount[$goods->id]['money'];
                        }
                        $_price = $discountPrice > 0 ? $discountPrice : 0.01;
                        $price +=  $_price;
                        $totalPrice += $goods->price;

                        $orderGoodsList[] = [
                            'type' => $goods->type,
                            'goods_id' => $goods->id,
                            'goods_no' => $goods->goods_no,
                            'title' => $goods->title,
                            'short_title' => $goods->short_title,
                            'pinyin_title' => $goods->pinyin_title,
                            'image' => $goods->image,
                            'goods_category_id' => $goods->goods_category_id,
                            'biaoben_type_id' => $goods->biaoben_type_id,
                            'num' => $goods->num,
                            'biaoben_rongqi_id' => $goods->biaoben_rongqi_id,
                            'keshi' => $goods->keshi,
                            'fangfa' => $goods->fangfa,
                            'waijian_tags' => $goods->waijian_tags,
                            'hospital' => $goods->hospital,
                            'time' => $goods->time,
                            'real_price' => $_price,
                            'price' => $goods->price,
                            'original_price' => $goods->original_price,
                            'discount_type' => $discount_type,
                            'discount' => $discount,
                        ];
                    }

                    $saveGoodsItemList = [];
                    foreach ($goodsItemList as $goods) {
                        $saveGoodsItemList[] = [
                            'type' => $goods->type,
                            'goods_id' => $goods->id,
                            'goods_no' => $goods->goods_no,
                            'title' => $goods->title,
                            'short_title' => $goods->short_title,
                            'pinyin_title' => $goods->pinyin_title,
                            'image' => $goods->image,
                            'goods_category_id' => $goods->goods_category_id,
                            'biaoben_type_id' => $goods->biaoben_type_id,
                            'num' => $goods->num,
                            'biaoben_rongqi_id' => $goods->biaoben_rongqi_id,
                            'keshi' => $goods->keshi,
                            'fangfa' => $goods->fangfa,
                            'waijian_tags' => $goods->waijian_tags,
                            'hospital' => $goods->hospital,
                            'time' => $goods->time,
                            'price' => $goods->price,
                            'original_price' => $goods->original_price,
                        ];
                    }

                    if (count($rongqiList) != count($tubeData)) {
                        $this->error('试管容器数量有误');
                    }

                    $params = $row;
                    $order_sn = createOrdersn($user->id, 'O');
                    $params['out_trade_no'] = $order_sn;
                    $params['order_sn'] = $order_sn;
                    $params['original_price'] = $totalPrice;
                    $params['price'] = $price;
                    $params['pay_type'] = 30;
                    $params['pay_status'] = 1;
                    $params['pay_time'] = time();
                    $params['status'] = 10;
                    $params['sole_id'] = $hospital->user_id;
                    $params['hospital_id'] = $hospital->id;

                    $result = $this->model->allowField(true)->save($params);
                    $modelMaster = $this->model->find($this->model->id);

                    $tubeSaveList = [];
                    foreach ($tubeData as $tube) {
                        $tubeSaveList[] = [
                            'order_master_id' => $this->model->id,
                            'biaoben_rongqi_id' => $tube['id'],
                            'tube_number' => $tube['tube_number']
                        ];
                    }
                    $orderTube = new \app\api\model\order\OrderTube();
                    $orderTubeList = $orderTube->saveAll($tubeSaveList);
                    if (!$orderTubeList) {
                        throw new \Exception('订单创建失败');
                    }

                    foreach ($orderGoodsList as &$item) {
                        $item['order_master_id'] = $this->model->id;
                    }

                    $orderGOods = new \app\api\model\order\OrderGoods();
                    $orderGoodsListModel = $orderGOods->saveAll($orderGoodsList);
                    if (!$orderGoodsListModel) {
                        throw new \Exception('订单创建失败');
                    }

                    foreach ($orderGoodsListModel as $orderGoods) {
                        $order = new \app\api\model\order\Order();
                        $result = $order->save([
                            'order_master_id' => $modelMaster->id,
                            'order_goods_id' => $orderGoods->id,
                            'user_id' => $modelMaster->user_id,
                            'sole_id' => $modelMaster->sole_id,
                            'hospital_id' => $modelMaster->hospital_id,
                            'username' => $modelMaster->username,
                            'userphone' => $modelMaster->userphone,
                            'age' => $modelMaster->age,
                            'gender' => $modelMaster->gender,
                            'out_trade_no' => $modelMaster->out_trade_no,
                            'transaction_id' => $modelMaster->transaction_id,
                            'order_sn' => createOrdersn($modelMaster->user_id, 'S'),
                            'price' => $orderGoods->real_price,
                            'original_price' => $orderGoods->price,
                            'pay_type' => $modelMaster->pay_type,
                            'order_type' => 10,
                            'pay_status' => 1,
                            'pay_time' => time(),
                            'status' => 10,
                        ]);

                        if (!$result) {
                            \think\Log::record("子订单保存失败：{$order->out_trade_n}-{$orderGoods->id}");
                            throw new \Exception("子订单保存失败：{$order->out_trade_n}-{$orderGoods->id}");
                        }
                    }

                    $saveGoodsItemListIds = [];
                    $saveGoodsItemListData = [];
                    foreach ($saveGoodsItemList as &$item) {
                        $item['order_master_id'] = $this->model->id;
                        if (!in_array($item['goods_id'], $saveGoodsItemListIds)) {
                            $saveGoodsItemListIds[] = $item['goods_id'];
                            $saveGoodsItemListData[] = $item;
                        }
                    }
                    $orderGoodsItem = new \app\api\model\order\OrderGoodsItem();
                    $orderGoodsItemListModel = $orderGoodsItem->saveAll($saveGoodsItemListData);
                    if (!$orderGoodsItemListModel) {
                        throw new \Exception('订单创建失败');
                    }

                    if (count($saveOrderGoodsDetails)) {
                        foreach ($saveOrderGoodsDetails as &$item) {
                            $item['order_master_id'] = $this->model->id;
                        }
                        $orderGoodsDetails = new \app\api\model\order\OrderGoodsDetails();
                        $orderGoodsDetailsListModel = $orderGoodsDetails->saveAll($saveOrderGoodsDetails);
                        if (!$orderGoodsDetailsListModel) {
                            throw new \Exception('订单创建失败');
                        }
                    }
                    Db::commit();
                    
                }
            }
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

        // try {
        //     //是否包含admin_id字段
        //     $has_admin_id = false;
        //     foreach ($fieldArr as $name => $key) {
        //         if ($key == 'admin_id') {
        //             $has_admin_id = true;
        //             break;
        //         }
        //     }
        //     if ($has_admin_id) {
        //         $auth = Auth::instance();
        //         foreach ($insert as &$val) {
        //             if (empty($val['admin_id'])) {
        //                 $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
        //             }
        //         }
        //     }

        //     $l = $this->model->allowField(true)->saveAll($insert);
        //     foreach ($l as $item){
        //         if(isset($goods_no_list[$item->goods_no])){
        //             $saveData = [];
        //             foreach ($goods_no_list[$item->goods_no] as $goods_id){
        //                 $saveData[] = [
        //                     'goods_master_id' => $item->id,
        //                     'goods_id' => $goods_id,
        //                     'type'=>$item->type
        //                 ];
        //             }
        //             \app\admin\model\goods\GoodsDetails::insertAll($saveData);
        //         }
        //     }
        // } catch (PDOException $exception) {
        //     $msg = $exception->getMessage();
        //     if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
        //         $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
        //     };
        //     $this->error($msg);
        // } catch (Exception $e) {
        //     $this->error($e->getMessage());
        // }
        $this->success('导入成功');
    }

}
